﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HZY.Logic.Sys
{
    using System.Linq;
    using System.Threading.Tasks;
    using System.Collections;
    using HZY.DbExtensions;
    using HZY.Models.Sys;
    using HZY.Models;
    using HZY.Toolkit;
    using HZY.DTO.Sys;
    using HZY.Logic.Core;
    using Newtonsoft.Json;
    using Microsoft.AspNetCore.Http;
    using System.Security.Claims;
    using System.IO;

    public class AccountLogic : LogicBase
    {
        public Account UserAccount { get; }

        public HttpContext httpContext { get; }

        public AccountLogic(HzySqlDbContext dbContext, IHttpContextAccessor iHttpContextAccessor)
            : base(dbContext)
        {
            this.httpContext = iHttpContextAccessor.HttpContext;

            if (httpContext.User != null)
            {
                var claimsIdentity = httpContext.User.Identity as ClaimsIdentity;
                if (claimsIdentity.Name != null)
                {
                    var Id = claimsIdentity.Name;
                    this.UserAccount = this.GetAccountByUserId(Id.ToGuid()).Result;
                }

            }
        }

        /// <summary>
        /// 账号检查
        /// </summary>
        /// <param name="uName"></param>
        /// <param name="uPwd"></param>
        /// <param name="loginCode"></param>
        public async Task<string> CheckedAsync(string uName, string uPwd, string loginCode)
        {
            if (string.IsNullOrEmpty(uName)) throw new MessageBox("请输入用户名");
            if (string.IsNullOrEmpty(uPwd)) throw new MessageBox("请输入密码");
            //if (string.IsNullOrEmpty(loginCode)) throw new MessageBox("请输入验证码");

            var _Sys_User = await db.Query<Sys_User>(w => w.t1.User_LoginName == uName).FirstAsync();

            if (_Sys_User == null) throw new MessageBox("用户不存在");
            //Tools.MD5Encrypt(userpwd)))//
            if (_Sys_User.User_Pwd.ToStr().Trim() != uPwd) throw new MessageBox("密码错误");
            //string code = Tools.GetCookie("loginCode");
            //if (string.IsNullOrEmpty(code)) throw new MessageBox("验证码失效");
            //if (!code.ToLower().Equals(loginCode.ToLower())) throw new MessageBox("验证码不正确");

            return new JwtTokenUtil().GetToken(_Sys_User.User_ID.ToStr(), AppConfig.AdminConfig.JwtSecurityKey, AppConfig.AdminConfig.JwtKeyName);
        }

        /// <summary>
        /// 根据用户信息获取 Account 对象
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<Account> GetAccountByUserId(Guid Id)
        {
            var _Sys_User = await db.FindByIdAsync<Sys_User>(Id);
            var _Account = new Account();
            var _Sys_UserRole = await db.Query<Sys_UserRole>(w => w.t1.UserRole_UserID == _Sys_User.User_ID).ToListAsync();
            //
            _Account.RoleIDList = _Sys_UserRole.Select(w => w.UserRole_RoleID.ToGuid()).ToList();
            _Account.UserID = _Sys_User.User_ID.ToGuid();
            _Account.UserName = _Sys_User.User_Name;
            _Account._Sys_User = _Sys_User;
            //如果是超级管理员 帐户
            _Account.IsSuperManage = _Sys_UserRole.Any(w => w.UserRole_RoleID == AppConfig.AdminConfig.AdminRoleID);
            return _Account;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <param name="newlypwd"></param>
        public async Task ChangePwd(string oldpwd, string newpwd)
        {
            if (string.IsNullOrEmpty(oldpwd)) throw new MessageBox("旧密码不能为空");
            if (string.IsNullOrEmpty(newpwd)) throw new MessageBox("新密码不能为空");
            var _Sys_User = await db.FindByIdAsync<Sys_User>(UserAccount.UserID);
            if (_Sys_User.User_Pwd != oldpwd) throw new MessageBox("旧密码不正确");

            await db.Update(() => new Sys_User { User_Pwd = newpwd })
                .Where(w => w.t1.User_ID == UserAccount.UserID)
                .SaveAsync()
                ;
        }

        /// <summary>
        /// 写入操作日志
        /// </summary>
        public async Task InsertAppLogAsync()
        {
            var _QueryString = httpContext.Request.QueryString.ToString();
            var _ApiUrl = httpContext.Request.Path;
            var _IP = httpContext.Connection.RemoteIpAddress.ToString();

            //本机不记录
            // if (_IP == "::1") return;

            var body = string.Empty;
            var form = string.Empty;

            //body
            try
            {
                //读取 body 信息
                // var reader = new StreamReader(httpContext.Request.Body);
                // body = await reader.ReadToEndAsync();

                Stream stream = httpContext.Request.Body;
                byte[] buffer = new byte[httpContext.Request.ContentLength.Value];
                await stream.ReadAsync(buffer, 0, buffer.Length);
                body = Encoding.UTF8.GetString(buffer);
            }
            catch (Exception)
            {

            }
            //form
            try
            {
                //读取 表单 信息
                var _Form = httpContext.Request.Form;
                if (_Form != null)
                {
                    var _Dictionary = new Dictionary<string, object>();
                    foreach (var key in _Form.Keys)
                    {
                        _Dictionary[key] = _Form[key];
                    }

                    form = JsonConvert.SerializeObject(_Dictionary);
                }

            }
            catch (Exception) { }

            await db.Insert(new Sys_AppLog
            {
                AppLog_Api = _ApiUrl,
                AppLog_IP = _IP,
                AppLog_Form = form,
                AppLog_QueryString = _QueryString,
                AppLog_FormBody = body,
                AppLog_UserID = UserAccount?.UserID
            }).SaveAsync();
        }




    }
}
